﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using CashOrCard.Models;
using CashOrCard.Helper;

namespace CashOrCard.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                if (Common.isApproved)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return RedirectToAction("ActiveAccount");
                }
            }
            else
            {
                ViewBag.ShowBanner = true;
                ViewData["accountItems"] = Common.GetRoleList();
                var tuple = new Tuple<Login, Register>(new Login(), new Register());
                return View(tuple);
            }
        }

        [HttpPost]
        public JsonResult Pop_login(string email, string password, bool rememberMe)
        {
            using (CashOrCardContext objContext = new CashOrCardContext())
            {
                var objUser = objContext.Users.FirstOrDefault(x => x.Email == email && x.IsEnable == true);
                if (objUser == null)
                {
                    return Json(new { result = "failed", errormsg = "Incorrect Email, Please check." });                    
                }
                else
                {
                    if (HashUtility.ValidateMD5HashData(password, objUser.Password))
                    {
                        FormsAuthentication.SetAuthCookie(email, rememberMe);
                        string userName = string.IsNullOrEmpty(objUser.FirstName)? objUser.Email: string.Format("{0} {1}", objUser.FirstName, objUser.LastName);
                        return Json(new { result = "success", errormsg = "Incorrect Password, Please check.", username=userName }); 
                    }
                    else
                    {
                        return Json(new { result = "failed", errormsg = "Incorrect Password, Please check." });   
                    }
                }
            }
        }

        [HttpPost]
        public JsonResult auth_user()
        {
            if (Request.IsAuthenticated)
            {
                return Json(new { result = "success" });
            }
            else
            {
                return Json(new { result = "failed" });
            }
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Tuple<Login, Register> model, string returnUrl)
        {          
            if (ModelState.IsValid)
            {                
                using (CashOrCardContext objContext = new CashOrCardContext())
                {
                    var objUser = objContext.Users.FirstOrDefault(x => x.Email == model.Item1.Email && x.IsEnable == true);
                    if (objUser == null)
                    {
                        ModelState.AddModelError("Login Error", "Incorrect Email, Please check.");
                        ViewBag.LoginErrorMsg = "Incorrect Email, Please check.";
                    }
                    else
                    {
                        if (HashUtility.ValidateMD5HashData(model.Item1.Password, objUser.Password))
                        {
                            FormsAuthentication.SetAuthCookie(model.Item1.Email, model.Item1.RememberMe);
                            if (objUser.IsApproved)
                            {
                                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                                {
                                    return Redirect(returnUrl);
                                }
                                else
                                {
                                    //Redirect to default page                    
                                    return RedirectToAction("RedirectToDefault");
                                }
                            }
                            else
                            {
                                return RedirectToAction("ActiveAccount");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("Login Error", "Incorrect Password, Please check");
                            ViewBag.LoginErrorMsg = "Incorrect Password, Please check";
                        }
                    }
                }

            }

            
            // If we got this far, something failed, redisplay form     
            ViewData["accountItems"] = Common.GetRoleList(); 
            ViewBag.validationform = "login";
            return View("index", model);
        }

        [HttpGet]
        public ActionResult Register()
        {
            ViewData["accountItems"] = Common.GetRoleList(); 
            return RedirectToAction("index");            
        }

        [HttpGet]
        public ActionResult Login()
        {
            ViewData["accountItems"] = Common.GetRoleList(); 
            return RedirectToAction("index");
        }

        [HttpPost]
        public ActionResult ActiveAccount()
        {
            decimal dAmount = 1;
            int userId = Common.CurrentUser.UserId;
            string userEmail = Common.CurrentUserEamil;
            string itemName = "Active BusinessOwner Account";
            string itemDescription = "Active Account $" + dAmount + " to account";
            string currency = ConfigurationManager.AppSettings["Currency"];
            int paypalId = 0;
            using (CashOrCardContext dbContext = new CashOrCardContext())
            {
                PaymentHistory payPalObj = new PaymentHistory();
                payPalObj.PaymentAmount = dAmount;
                payPalObj.Currency = currency;
                payPalObj.PaymentType = PaymentType.Register.ToString();
                payPalObj.UserId = userId;
                payPalObj.UserEmail = userEmail;
                payPalObj.ItemName = itemName;
                payPalObj.PaymentComment = itemDescription;
                payPalObj.PaymentDate = DateTime.Now;
                dbContext.PaymentHistorys.Add(payPalObj);
                dbContext.SaveChanges();

                paypalId = payPalObj.PaymentId;
            }
            string paypalUrl = IsTestMode ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
                : "https://www.paypal.com/cgi-bin/webscr";
            
            ViewBag.Amount = dAmount;
            ViewBag.OrderId = paypalId;
            ViewBag.ItemName = itemName;
            //ViewBag.ItemDescription = itemDescription;
            ViewBag.Currecy = currency;
            ViewBag.Email = userEmail;
            ViewBag.Business = ConfigurationManager.AppSettings["PaypalBusinessEmail"];
            ViewBag.SiteURL = ConfigurationManager.AppSettings["SiteURL"];
            ViewBag.PaypalURL = paypalUrl;
            ViewBag.SubmitForm = true;

            return View();
        }

        [HttpGet]
        [ActionName("ActiveAccount")]
        public ActionResult ActiveAccount_Get()
        {
            ViewBag.SubmitForm = false;
            return View();
        }

        private bool IsTestMode
        {
            get
            {
                bool isTest = false;
                bool.TryParse(ConfigurationManager.AppSettings["PaypalTestMode"], out isTest);
                return isTest;
            }
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(Tuple<Login, Register> model, string returnUrl)
        {   
            if (ModelState.IsValid)
            {
                using (CashOrCardContext objContext = new CashOrCardContext())
                {
                    if (objContext.Users.Where(x => x.Email.Equals(model.Item2.Email)).Count() > 0)
                    {
                        ModelState.AddModelError("Login Error", "Existed Email, Please use another one");
                        ViewBag.LoginErrorMsg = "Existed Email, Please use another one";
                    }
                    else
                    {
                        int selectedAccoutTypeId = int.Parse(model.Item2.AccountType);
                        Role role = objContext.Roles.First(x => x.RoleId.Equals(selectedAccoutTypeId));

                        User user = new User
                        {
                            Email = model.Item2.Email,
                            Password = HashUtility.GetMD5HashData(model.Item2.Password),
                            Role = role,
                            CreateDate = DateTime.Now,
                            IsEnable = true,
                            FirstName = model.Item2.FirstName,
                            LastName = model.Item2.LastName
                        };

                        if (Common.GetUserType(role.RoleName) == EnumUserType.BusinessOwner)
                        {
                            //For Business Owner, they should paid regiter fee before account actived.
                            user.IsApproved = false;
                        }
                        else
                        {
                            user.IsApproved = true;
                        }

                        objContext.Users.Add(user);
                        objContext.SaveChanges();


                        FormsAuthentication.SetAuthCookie(model.Item2.Email, false);

                        if (user.IsApproved)
                        {
                            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                //Redirect to default page                    
                                return RedirectToAction("RedirectToDefault");
                            }
                        }
                        else
                        {
                            return RedirectToAction("ActiveAccount");
                        }
                    }
                }
            }

            ViewData["accountItems"] = Common.GetRoleList(); 

            ViewBag.validationform = "register";
            return View("index", model);
        }

        public ActionResult RedirectToDefault()
        {
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();            
            return RedirectToAction("Index", "Home");
        }      

    }
}
